<div class="panel panel-default main">
  <div class="panel-heading">0~100带括号整数四则运算</div>
  <div class="panel-body">
    <center>
      <div>
        <form action="doComputeTable" id="itemForm">
          <table class="table table-striped table-bordered table-hover"
            id="formula-table">
            <thead>
              <th>#</th>
              <th><center>运算式</center></th>
              <th></th>
              <th>结果</th>
              <th>判断</th>
            </thead>
            <tbody id="formula-table-body">
            </tbody>
          </table>
      </div>
      <div class="btn-group">
        <a href="#" class="btn btn-primary btn-create" role="button">生成运算式子</a>
        <a href="#" class="btn btn-info btn-submit" role="button">提交</a>
        <a href="#" class="btn btn-success btn-history" role="button">历史查询</a>
        <a href="#" class="btn btn-default btn-next" role="button">再来一次</a>
      </div>
      </form>
    </center>
  </div>
</div>
<script type="text/javascript">
$(function(){
	$(".btn-group").on("click",".btn-create",doCreateZeroHundred)
		.on("click",".btn-submit",subminFormula);
	
	doCreateZeroHundred();
})

/**提交**/
function subminFormula(){
	var formulas = $("#formula-table-body").data("formula");
	var flag = checkAnserEmpty(formulas);
	
	if(!flag){
		return;
	}
	for(var row of formulas){
		var userAnswer = $("#user-answer"+row.id).val();
		console.log(userAnswer+":"+row.answer)
		if(userAnswer == row.answer){
			$("#failOrTrue"+row.id).html("<i class='fa fa-check' aria-hidden='true'></i>");
		}else{
			$("#failOrTrue"+row.id).html("<i class='fa fa-times' aria-hidden='false'></i>");
		}
	}
}
/*检验是否填写完全答案*/
function checkAnserEmpty(formulas){
	for(var row of formulas){
		//获取输入的答案
		var userAnswer = $("#user-answer"+row.id).val();
		if(!userAnswer){
			alert("答案还没有填写完全！");
			return 0;
		}
	}
	return 1;
}
/*生成算式*/
function doCreateZeroHundred(){
	var url = "doCreateWithBracket";
	//待定，让用户可以自己确定生成多少行
	var params = {"count":20};
	
	$.getJSON(url,params,function(result){
		//alert(result.message);
		if(result.state==1){
			doSetTableRows(result.data);
		}else{
			alert("error");
		}
	})
}
function doSetTableRows(data){
	var body = $("#formula-table-body");
	body.empty();
	body.data("formula",data);
	
	for(let row of data){
		let tr = $("<tr></tr>");
		let tds = doCreateTds(row);
		tr.append(tds);
		body.append(tr);
	}
}
function doCreateTds(data){
    var tds =
    	"<td id='id"+data.id+"'>"+data.id+"</td>"+
        "<td>"+data.equation+"</td>"+
        "<td>=</td>"+
        "<td><input type='text' id='user-answer"+data.id+"'/></td>"+
        //"<td class='current-answer'>"+data.answer+"</td>";
        "<td id='failOrTrue"+data.id+"'></td>";
        
    
    return tds;
}
</script>